﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Pub;
using System.Configuration;
using System.Threading;
using LZQXT.Test.Forms.DB;
using ICSharpCode.TextEditor;
using ICSharpCode.TextEditor.Document;

namespace LZQXT.Test.Forms
{
    public partial class FDBMgr : Form
    {


        public delegate void tv1AddNodeCallBack(TreeNodeDBMgr node1);
        public delegate void tv1ClsCallBack();

        ADOTest ado1 = new ADOTest();
        ADOTest ado2 = new ADOTest();



        //CDB.DBInfo dbInf = new CDB.DBInfo();

        DataSet ds1 = null;
        int i_RowIndex = 0;

        FDBRow fdbrow = new FDBRow();

        public TextEditorControl tboxSQL;
        public CTextEditMenu tboxSQL_Menu;
        public CGridViewMenu gridMenu;


        private void FQuery_Load(object sender, EventArgs e)
        {

            dataGridView1.Dock = DockStyle.Fill;
            dataGridView2.Dock = DockStyle.Fill;
            treeView1.Dock = DockStyle.Fill;
            //tabControl1.Dock = DockStyle.Fill;
            tabControl2.Dock = DockStyle.Fill;
            panel_Sel.Dock = DockStyle.Fill;
            tbox_Msg.Dock = DockStyle.Fill;
            panel_Center.Dock = DockStyle.Fill;

            /*
            fdbrow.FormBorderStyle = FormBorderStyle.None;
            fdbrow.TopLevel = false;
            fdbrow.Parent = tabPage_Field;
            fdbrow.Dock = DockStyle.Fill;
            fdbrow.Show();
            fdbrow.tabControl1.Alignment = TabAlignment.Left;
            */

            //创建查询编辑器窗口
            panel_SQL.Dock = DockStyle.Fill;
            tboxSQL = new TextEditorControl();
            tboxSQL.BorderStyle = BorderStyle.Fixed3D;
            tboxSQL.Parent = panel_SQL;
            tboxSQL.Dock = DockStyle.Fill;
            tboxSQL.Show();

            tboxSQL.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy("TSQL");
            tboxSQL.Encoding = System.Text.Encoding.Default;
            tboxSQL.ActiveTextAreaControl.TextArea.KeyDown += tbox_KeyDown;

            tabControl1.SelectedIndex = 0;



            tboxSQL_Menu = new CTextEditMenu(tboxSQL);
            gridMenu = new CGridViewMenu(dataGridView1, ado1);
        }

        private void FQuery_Shown(object sender, EventArgs e)
        {
            //Thread thread1 = new Thread(fillTree);
            //thread1.Start();
            //fillTree();
        }


        public void tv1AddNode(TreeNodeDBMgr node1)
        {
            try
            {
                if (treeView1.InvokeRequired)
                {
                    tv1AddNodeCallBack tbc = new tv1AddNodeCallBack(tv1AddNode);
                    this.Invoke(tbc, new object[] { node1 });
                }
                else
                {
                    treeView1.Nodes.Add(node1);
                }
            }
            catch (System.Exception ex)
            {
                CDebug.SendError(ex.ToString());
            }
        }

        public void tv1Cls()
        {
            try
            {
                if (treeView1.InvokeRequired)
                {
                    tv1ClsCallBack tbc = new tv1ClsCallBack(tv1Cls);
                    this.Invoke(tbc, new object[] { });
                }
                else
                {
                    treeView1.Nodes.Clear();
                }
            }
            catch (System.Exception ex)
            {
                CDebug.SendError(ex.ToString());
            }
        }

        public FDBMgr()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 按钮及右键菜单事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Click(object sender, EventArgs e)
        {
            int i_btn = 0;
            if (sender is Button) i_btn = Convert.ToInt32(((Button)sender).Tag);
            if (sender is ToolStripButton) i_btn = Convert.ToInt32(((ToolStripButton)sender).Tag);
            if (sender is ToolStripMenuItem) i_btn = Convert.ToInt32(((ToolStripMenuItem)sender).Tag);
            if (sender is Int32) i_btn = Convert.ToInt32(sender);
            if (sender is MenuItem) i_btn = Convert.ToInt32(((MenuItem)sender).Tag);

            String strSQL = "";

            switch (i_btn)
            {
                case 1:     //执行select语句
                    #region 执行sql语句
                    try
                    {
                        TreeNodeDBMgr node1 = (TreeNodeDBMgr)treeView1.SelectedNode;
                        if (tboxSQL_Menu.SelectedText.Length > 0) strSQL = tboxSQL_Menu.SelectedText;
                        else strSQL = tboxSQL.Text;

                        strSQL = strSQL.Replace("\r", " ");
                        strSQL = strSQL.Replace("\n", " ");
                        ds1 = ado1.sel1(strSQL);

                        //数据库名称
                        string sDBNam_temp = CPub.findStrBetween(strSQL.Replace("\n", " ").ToLower(), "use", "").Trim();
                        string sDBNam_temp_2 = CPub.findStrBetween(sDBNam_temp, "", " ");
                        if (sDBNam_temp_2 != "") node1.dbInf.sDBNam = sDBNam_temp_2;
                        else if (sDBNam_temp != "") node1.dbInf.sDBNam = sDBNam_temp;
                        //表名
                        string sTabNam_temp = CPub.findStrBetween(strSQL.Replace("\n", " ").ToLower(), "from", "").Trim();
                        string sTabNam_temp_2 = CPub.findStrBetween(sTabNam_temp, "", " ");
                        if (sTabNam_temp_2 != "") node1.dbInf.sTable = sTabNam_temp_2;
                        else node1.dbInf.sTable = sTabNam_temp;

                        labDBName.Text = node1.dbInf.sDBNam;
                        labTabName.Text = node1.dbInf.sTable;
                        gridMenu.sTableName = node1.dbInf.sTable;

                        //显示数据
                        if (ds1 != null && ds1.Tables.Count > 0) dataGridView1.DataSource = ds1.Tables[0];
                        else dataGridView1.DataSource = null;

                        tbox_Msg.Text = "(" + ado1.ds_count + "受影响)";
                        labCount.Text = "(" + ado1.ds_count + "受影响)";
                        tabControl1.SelectedTab = tabPage_Grid;
                    }
                    catch (System.Exception ex)
                    {
                        dataGridView1.DataSource = null;
                        CDebug.EnterMethod("发生异常");
                        CDebug.Send(strSQL);
                        CDebug.SendError(ex.ToString());
                        //tboxSQL_Menu.AppendText("-- " + ex.ToString());
                        tbox_Msg.Text = ex.Message;
                        tabControl1.SelectedTab = tabPage_Msg;

                        CDebug.ExitMethod("发生异常");
                    }
                    #endregion
                    break;
                case 2:     //执行update,insert,delete语句
                    #region 执行update,insert,delete语句
                    try
                    {
                        if (tboxSQL_Menu.SelectedText.Length > 0) strSQL = tboxSQL_Menu.SelectedText;
                        else strSQL = tboxSQL.Text;

                        int i_Update_Count = 0;
                        string[] s1 = strSQL.Split('\n');
                        string s2 = "";
                        if (s1.Length > 10)
                        {
                            for (int i = 0; i < 10; i++)
                                s2 += s1[i] + "\n";
                            s2 += "……";
                        }
                        else
                        {
                            for (int i = 0; i < s1.Length; i++)
                                s2 += s1[i] + "\n";
                        }

                        if (CPub.MsgBox("确定要更新数据库吗？\n" + s2, "更新"))
                        {
                            i_Update_Count = ado1.cmd1(strSQL);
                        }
                        tbox_Msg.Text = "(" + i_Update_Count + "受影响)";
                        tabControl1.SelectedTab = tabPage_Msg;
                    }
                    catch (System.Exception ex)
                    {
                        dataGridView1.DataSource = null;
                        CDebug.EnterMethod("发生异常");
                        CDebug.Send(strSQL);
                        CDebug.SendError(ex.ToString());
                        //tboxSQL_Menu.AppendText("-- " + ex.ToString());
                        tbox_Msg.Text = ex.Message;
                        tabControl1.SelectedTab = tabPage_Msg;

                        CDebug.ExitMethod("发生异常");
                    }
                    #endregion
                    break;

                case 11:
                    //Thread thread1 = new Thread(fillTree);
                    //thread1.Start();
                    refTree();
                    break;
                case 12:
                    TreeNodeDBMgr node2 = (TreeNodeDBMgr)treeView1.SelectedNode;
                    setKey(node2.dbInf.sTable, node2.dbInf.sField);
                    break;
                case 13:
                    dropTable();
                    break;
                case 14:
                    exportSQL();
                    break;

                case 31:    //生成数据库连接字符串，填充树目录
                    #region 连接服务器
                    try
                    {
                        string sDBCon = "";
                        FDBLogin fdblogin = new FDBLogin();
                        CDB.DBInfo dbInf = new CDB.DBInfo();
                        fdblogin.ShowDialog(ref sDBCon, ref dbInf);
                        CDebug.Send(sDBCon);
                        if (sDBCon != null && sDBCon != "")
                        {
                            ado1.S_Con = sDBCon;
                            ado2.S_Con = sDBCon;

                            Boolean b_isSource = false;
                            for (int i = 0; i < treeView1.Nodes.Count; i++)
                            {
                                if (dbInf.sSourc == treeView1.Nodes[i].Text)
                                {
                                    b_isSource = true;
                                    break;
                                }
                            }

                            if (b_isSource) MessageBox.Show("该服务器连接已存在！");
                            else
                            {
                                try
                                {
                                    //填充数据库名称
                                    ADOTest ado_Test = new ADOTest();
                                    ado_Test.S_Con = ado1.S_Con;
                                    DataSet ds1 = ado_Test.sel1("SELECT Name FROM Master..SysDatabases ORDER BY Name");
                                    if (ds1 != null || ds1.Tables.Count > 0)
                                    {
                                        TreeNodeDBMgr node0 = new TreeNodeDBMgr();
                                        node0.Text = dbInf.sSourc;
                                        node0.Tag = 0;
                                        node0.ImageIndex = 0;
                                        node0.dbInf = dbInf;
                                        foreach (DataRow dr1 in ds1.Tables[0].Rows)
                                        {
                                            String DBName = dr1["Name"].ToString();
                                            TreeNodeDBMgr node1 = new TreeNodeDBMgr();
                                            node1.Text = DBName;
                                            node1.Tag = 1;
                                            node1.ImageIndex = 1;
                                            node1.dbInf = node0.dbInf;
                                            node1.dbInf.sDBNam = DBName;

                                            node0.Nodes.Add(node1);
                                        }
                                        treeView1.Nodes.Add(node0);
                                    }
                                }
                                catch (System.Exception ex)
                                {
                                    MessageBox.Show("连接服务器失败！");
                                    CDebug.SendError(ex.ToString());
                                }

                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        CDebug.SendError(ex.ToString());
                        MessageBox.Show(ex.Message);
                    }

                    #endregion
                    break;
                case 32:    //close ado
                    if (treeView1.SelectedNode != null) treeView1.SelectedNode.Remove();
                    break;
                case 33:    //refresh ado
                    btn_Click(11, null);
                    break;
                case 34:
                    Program.fdbinit.ShowDialog();
                    return;
            }
        }

        private void tbox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5)
            {
                btn_Click(btn_Select, null);
            }
        }

        /// <summary>
        /// 生成数据库名称，表名，字段名
        /// </summary>
        //private void fillTree()
        //{
        //    try
        //    {
        //        if (ado1.S_Con == null || ado1.S_Con == "") return;
        //        //treeView1.Nodes.Clear();
        //        tv1Cls();

        //        //Dictionary<string, string>.KeyCollection dicKey = ADOTest.dicConStr.Keys;

        //        //foreach (string sDBConKey in dicKey)
        //        //{
        //        //ADOTest ado_Test = new ADOTest(sDBConKey);
        //        ADOTest ado_Test = new ADOTest();
        //        ado_Test.S_Con = ado1.S_Con;
        //        DataSet ds1 = ado_Test.sel1("SELECT Name FROM Master..SysDatabases ORDER BY Name");
        //        if (ds1 != null || ds1.Tables.Count > 0)
        //        {
        //            TreeNodeDBMgr node0 = new TreeNodeDBMgr();
        //            node0.Text = CPub.findStrBetween(ado1.S_Con, "=", ";");
        //            node0.Tag = 0;
        //            node0.ImageIndex = 0;
        //            node0.dbInf = dbInf;
        //            foreach (DataRow dr1 in ds1.Tables[0].Rows)
        //            {
        //                String DBName = dr1["Name"].ToString();
        //                TreeNodeDBMgr node1 = new TreeNodeDBMgr();
        //                node1.Text = DBName;
        //                node1.Tag = 1;
        //                node1.ImageIndex = 1;
        //                node1.dbInf = node0.dbInf;
        //                node1.dbInf.sDBNam = DBName;

        //                node0.Nodes.Add(node1);
        //            }
        //            //treeView1.Nodes.Add(node0);
        //            tv1AddNode(node0);
        //        }

        //        //}
        //    }
        //    catch (System.Exception ex)
        //    {
        //        CDebug.SendError(ex.ToString());
        //        MessageBox.Show("连接数据库失败！");
        //    }

        //}

        private void refTree()
        {
            if (treeView1.SelectedNode == null)
            {
                //Thread thread1 = new Thread(fillTree);
                //thread1.Start();
            }
            else
            {
                TreeNodeDBMgr node1 = (TreeNodeDBMgr)treeView1.SelectedNode;
                if (Convert.ToInt32(node1.Tag) == 0)
                {
                    #region 服务器
                    //Thread thread1 = new Thread(fillTree);
                    //thread1.Start();
                    #endregion
                }
                if (Convert.ToInt32(node1.Tag) == 1)
                {
                    #region 数据库
                    node1.Nodes.Clear();
                    String DBName = node1.Text;
                    DataSet ds2 = ado1.sel1("SELECT Name FROM " + DBName + "..SysObjects Where XType='U' ORDER BY Name ");
                    if (ds2 != null && ds2.Tables.Count > 0)
                    {
                        foreach (DataRow dr2 in ds2.Tables[0].Rows)
                        {
                            String TabName = dr2["Name"].ToString();
                            TreeNodeDBMgr node2 = new TreeNodeDBMgr();
                            node2.Text = TabName;
                            node2.Tag = 2;
                            node2.ImageIndex = 2;
                            node2.dbInf = node1.dbInf;
                            node2.dbInf.sTable = TabName;

                            DataSet ds3 = ado1.sel1("SELECT Name FROM SysColumns WHERE id=Object_Id('" + TabName + "') ");
                            if (ds3 != null && ds3.Tables.Count > 0)
                            {
                                foreach (DataRow dr3 in ds3.Tables[0].Rows)
                                {
                                    String ColName = dr3["Name"].ToString();
                                    TreeNodeDBMgr node3 = new TreeNodeDBMgr();
                                    node3.Text = ColName;
                                    node3.Tag = 3;
                                    node3.ImageIndex = 3;
                                    node3.dbInf = node2.dbInf;
                                    node3.dbInf.sField = ColName;

                                    node2.Nodes.Add(node3);
                                }
                            }
                            node1.Nodes.Add(node2);
                        }
                    }

                    String strSQL = "SP_HELPDB " + node1.Text + "\n";
                    DataSet ds1 = ado2.sel1(strSQL);
                    if (ds1 == null || ds1.Tables.Count == 0)
                    {
                        dataGridView1.DataSource = null;
                        return;
                    }
                    if (ds1.Tables.Count > 1)
                        dataGridView2.DataSource = ds1.Tables[1];
                    #endregion

                }
            }

        }

        /// <summary>
        /// 创建主键，没有主键的表无法更新数据
        /// </summary>
        private void setKey(string sTab, string sCol)
        {
            CDebug.EnterMethod("设置主键");
            try
            {
                string sKeyName = "PK_" + sTab;
                string strSQL = "select * from sysobjects where name = '" + sKeyName + "'";
                DataSet ds1 = ado1.sel1(strSQL);

                //如果主键名称存在，则重命名
                int i = 1;
                while (ado1.ds_count > 0)
                {
                    sKeyName = "PK_" + sTab + "_" + i;
                    strSQL = "select * from sysobjects where name = '" + sKeyName + "'";
                    ds1 = ado1.sel1(strSQL);
                    i++;
                }

                strSQL = "ALTER TABLE [" + sTab + "] ADD  CONSTRAINT [" + sKeyName + "] PRIMARY KEY CLUSTERED \n"
                   + "( [" + sCol + "] ASC )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, \n"
                   + "IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]";
                CDebug.Send(strSQL);
                ado1.cmd1(strSQL);
            }
            catch (System.Exception ex)
            {
                CDebug.SendError("设置主键出错: " + ex.ToString());
            }

            CDebug.ExitMethod("设置主键");
        }

        /// <summary>
        /// 删除主键
        /// </summary>
        /// <param name="sTab"></param>
        /// <param name="sKey"></param>
        private void delKey(string sTab, string sKey)
        {
            CDebug.EnterMethod("删除主键");
            try
            {
                string strSQL = "ALTER " + sTab
                    + " DROP CONSTRAINT " + sKey + "\n "
                    + " ALTER TABLE " + sKey + " SET (LOCK_ESCALATION = TABLE) \n"
                    + " COMMIT ";
                CDebug.Send(strSQL);
                ado1.cmd1(strSQL);
            }
            catch (System.Exception ex)
            {
                CDebug.SendError("删除主键出错: " + ex.ToString());
            }

            CDebug.ExitMethod("删除主键");

        }

        private void dropTable()
        {
            TreeNodeDBMgr node1 = (TreeNodeDBMgr)treeView1.SelectedNode;
            if (CPub.MsgBox("确定要删除表[" + node1.dbInf.sTable + "]吗？", "删除"))
            {
                String strSQL = "DROP TABLE [" + node1.dbInf.sTable + "]";
                ado1.cmd1(strSQL);
                treeView1.SelectedNode.Remove();
            }

        }

        /// <summary>
        /// 展开节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            CDebug.EnterMethod("填充树目录");
            try
            {
                treeView1.SelectedNode.SelectedImageIndex = treeView1.SelectedNode.ImageIndex;

                if (treeView1.SelectedNode == null) return;
                TreeNodeDBMgr node1 = (TreeNodeDBMgr)treeView1.SelectedNode;
                int i_typ = Convert.ToInt32(node1.Tag);
                btn_Enable(i_typ);

                if (i_typ == 0)
                {
                    #region 服务器
                    node1.dbInf.sSourc = node1.Text;
                    #endregion
                }
                else if (i_typ == 1)
                {
                    #region 数据库
                    //node1.ImageIndex = 6;
                    //node1.SelectedImageIndex = node1.ImageIndex;
                    node1.dbInf.sSourc = node1.Parent.Text;
                    node1.dbInf.sDBNam = node1.Text;
                    strConReplace();

                    if (node1.Nodes.Count == 0)
                    {
                        CDebug.EnterMethod("填充数据库名称");
                        String DBName = node1.Text;
                        DataSet ds2 = ado1.sel1("SELECT Name FROM " + DBName + "..SysObjects Where XType='U' ORDER BY Name ");
                        if (ds2 != null && ds2.Tables.Count > 0)
                        {
                            foreach (DataRow dr2 in ds2.Tables[0].Rows)
                            {
                                String TabName = dr2["Name"].ToString();
                                TreeNodeDBMgr node2 = new TreeNodeDBMgr();
                                node2.Text = TabName;
                                node2.Tag = 2;
                                node2.ImageIndex = 2;
                                node2.dbInf = node1.dbInf;
                                node2.dbInf.sTable = TabName;

                                node1.Nodes.Add(node2);
                            }
                        }
                        CDebug.ExitMethod("填充数据库名称");
                    }

                    //String strSQL = "SP_HELPDB " + node1.dbInf.sDBNam + "\n";
                    //DataSet ds1 = ado2.sel1(strSQL);
                    //if (ds1 == null || ds1.Tables.Count == 0) dataGridView1.DataSource = null;
                    //else dataGridView2.DataSource = ds1.Tables[1];

                    #endregion
                }
                else if (i_typ == 2)
                {
                    #region 表
                    node1.dbInf.sSourc = node1.Parent.Parent.Text;
                    node1.dbInf.sDBNam = node1.Parent.Text;
                    node1.dbInf.sTable = node1.Text;
                    strConReplace();

                    if (node1.Nodes.Count == 0)
                    {
                        string strSQL_0 = "SELECT Name FROM SysColumns WHERE id=Object_Id('" + node1.dbInf.sTable + "') ";
                        DataSet ds3 = ado1.sel1(strSQL_0);
                        CDebug.Send(strSQL_0 + "\n返回结果个数: " + ado1.ds_count);
                        if (ds3 != null && ds3.Tables.Count > 0)
                        {
                            foreach (DataRow dr3 in ds3.Tables[0].Rows)
                            {
                                String ColName = dr3["Name"].ToString();
                                TreeNodeDBMgr node3 = new TreeNodeDBMgr();
                                node3.Text = ColName;
                                node3.Tag = 3;
                                node3.ImageIndex = 3;
                                node3.dbInf = node1.dbInf;
                                node3.dbInf.sField = ColName;

                                node1.Nodes.Add(node3);
                            }
                        }
                    }

                    string strSQL = "SELECT \n"
                        + "(case when a.colorder=1 then d.name else '' end) as 表名, \n"
                        + "  a.colorder as 字段序号, \n"
                        + "  a.name as 字段名, \n"
                        + "  (case when COLUMNPROPERTY( a.id,a.name, 'IsIdentity' )=1 then '√' else '' end) as 标识,  \n"
                        + "  (case when (SELECT count(*) FROM sysobjects \n"
                        + "    WHERE (name in \n"
                        + "      (SELECT name FROM sysindexes \n"
                        + "      WHERE (id = a.id)   AND (indid in \n"
                        + "        (SELECT indid FROM sysindexkeys \n"
                        + "          WHERE (id = a.id) AND (colid in \n"
                        + "            (SELECT colid FROM syscolumns \n"
                        + "            WHERE (id = a.id) AND (name = a.name)) \n"
                        + "    ))))) \n"
                        + "  AND (xtype = 'PK' ))>0 then '√' else '' end) as 主键, \n"
                        + "b.name as 类型, \n"
                        + "a.length as 占用字节数,  \n"
                        + "COLUMNPROPERTY(a.id,a.name,'PRECISION' ) as    长度,  \n"
                        + "isnull(COLUMNPROPERTY(a.id,a.name,'Scale' ),0) as 小数位数, \n"
                        + "(case when a.isnullable=1 then '√' else '' end) as 允许空, \n"
                        + "isnull(e.text,'' ) as 默认值, \n"
                        + "isnull(g.[value],'' ) AS 字段说明 \n"
                        + "FROM syscolumns a left join systypes b  \n"
                        + "on a.xtype=b.xusertype \n"
                        + "inner join sysobjects d \n"
                        + "on a.id=d.id and d.xtype='U' and d.name<> 'dtproperties'  \n"
                        + "left join syscomments e \n"
                        + "on a.cdefault=e.id \n"
                        + "left join sys.extended_properties g \n"
                        + "on a.id=g.major_id AND a.colid = g.minor_id  \n"
                        + "  where d.name='" + node1.dbInf.sTable + "' \n"
                        + "order by a.id,a.colorder \n";

                    CDebug.Send(strSQL);
                    DataSet ds1 = ado2.sel1(strSQL);
                    if (ds1 == null || ds1.Tables.Count == 0)
                    {
                        dataGridView1.DataSource = null;
                    }
                    else
                    {
                        dataGridView2.DataSource = ds1.Tables[0];
                        if (node1.Nodes.Count == 0)
                        {
                            CDebug.EnterMethod("填充字段名");
                            strSQL = "SP_HELP " + node1.dbInf.sTable + "\n";
                            DataSet ds2 = ado2.sel1(strSQL);
                            for (int i = 0; i < ds2.Tables[1].Rows.Count; i++)
                            {
                                DataRow dr1 = ds2.Tables[1].Rows[i];
                                String ColName = dr1["Column_name"].ToString();
                                TreeNodeDBMgr node3 = new TreeNodeDBMgr();
                                node3.Text = ColName;
                                node3.Tag = 3;
                                node3.ImageIndex = 3;
                                node3.dbInf = node1.dbInf;
                                node3.dbInf.sField = ColName;

                                node1.Nodes.Add(node3);
                            }
                            CDebug.ExitMethod("填充字段名");
                        }

                        foreach (TreeNodeDBMgr tn1 in node1.Nodes)
                        {
                            //判断是否为主键，如果为主键则显示主键图标
                            for (int j = 0; j < ds1.Tables[0].Rows.Count; j++)
                            {
                                if (ds1.Tables[0].Rows[j]["字段名"].ToString() == tn1.Text
                                    && ds1.Tables[0].Rows[j]["主键"].ToString() == "√")
                                {
                                    tn1.ImageIndex = 9;
                                }
                            }
                        }
                    }

                    #endregion
                }
                else if (i_typ == 3)
                {
                    #region 字段
                    node1.dbInf.sSourc = node1.Parent.Parent.Parent.Text;
                    node1.dbInf.sDBNam = node1.Parent.Parent.Text;
                    node1.dbInf.sTable = node1.Parent.Text;
                    node1.dbInf.sField = node1.Text;
                    strConReplace();

                    #endregion
                }
                labSource.Text = node1.dbInf.sSourc;
                labDBName.Text = node1.dbInf.sDBNam;
                labTabName.Text = node1.dbInf.sTable;
                gridMenu.sTableName = node1.dbInf.sTable;

            }
            catch (System.Exception ex)
            {
                CDebug.SendError(ex.ToString());
            }
            CDebug.ExitMethod("填充树目录");
        }

        /// <summary>
        /// 显示表中的数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_DoubleClick(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode == null) return;

            try
            {
                dataGridView1.DataSource = null;
                TreeNodeDBMgr node1 = (TreeNodeDBMgr)treeView1.SelectedNode;
                if (Convert.ToInt32(node1.Tag) == 2)
                {
                    /*
                    String strSQL = "USE " + node1.Parent.Text + "\n";
                    tboxSQL.AppendText(strSQL);
                    ado1.cmd1(strSQL);
                    */
                    string strSQL = "\n" + "USE " + node1.Parent.Text + "\n"
                        + "SELECT TOP 1000 * FROM " + node1.Text + "\n";
                    tboxSQL_Menu.AppendText(strSQL);
                    ds1 = ado1.sel1(strSQL);
                    if (ds1 != null || ds1.Tables.Count != 0)
                    {
                        dataGridView1.DataSource = ds1.Tables[0];
                    }

                    tbox_Msg.Text = "(" + ado1.ds_count + "受影响)";
                    labCount.Text = "(" + ado1.ds_count + "受影响)";
                    tabControl1.SelectedTab = tabPage_Grid;
                }
            }
            catch (System.Exception ex)
            {
                CDebug.SendError("查询数据出错: " + ex.ToString());
                tbox_Msg.Text = ex.ToString();
            }


        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            showFieldWindow();
        }

        public void showFieldWindow()
        {
            if (ds1.Tables.Count > 0)
            {
                TreeNodeDBMgr node1 = (TreeNodeDBMgr)treeView1.SelectedNode;
                fdbrow.field_Ref(ado1, node1.dbInf.sTable, dataGridView1, i_RowIndex);
                fdbrow.ShowDialog();
            }
        }

        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            i_RowIndex = e.RowIndex;
            //showFieldWindow();
        }

        public void btn_Enable(int i_Index)
        {
            //0 服务器；1 数据库；2 表；3 字段；
            int[,] i_Show = new int[,] { { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 1, 1, 1 }, { 1, 0, 1, 0 } };

            btnKey.Visible = Convert.ToBoolean(i_Show[i_Index, 0]);
            btnDropTable.Visible = Convert.ToBoolean(i_Show[i_Index, 1]);
            btnRef.Visible = Convert.ToBoolean(i_Show[i_Index, 2]);
            btnExport.Visible = Convert.ToBoolean(i_Show[i_Index, 3]);
        }

        /// <summary>
        /// 导出脚本
        /// </summary>
        public void exportSQL()
        {
            CDebug.EnterMethod("导出数据脚本");
            try
            {
                if (treeView1.SelectedNode != null)
                {
                    TreeNodeDBMgr node1 = (TreeNodeDBMgr)treeView1.SelectedNode;
                    int i_typ = Convert.ToInt32(node1.Tag);
                    string sTabName = node1.Text;
                    string strSQL = "SELECT TOP 3000 * FROM " + sTabName;
                    DataSet ds1 = ado1.sel1(strSQL);
                    if (!CDB.dsIsNull(ds1))
                    {
                        saveFileDialog1.FileName = sTabName + "_" + DateTime.Now.ToString("yyyy-MM-dd") + ".sql";
                        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                        {
                            List<string> lstSQL = new List<string>();
                            StringBuilder strSQL_Tem = new StringBuilder();
                            for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
                            {
                                DataRow dr = ds1.Tables[0].Rows[i];
                                strSQL_Tem.Append(CDB.getSQL_Insert(sTabName, dr, true, false));
                                //lstSQL.Add(strSQL_Tem);
                            }
                            CFile.Write(saveFileDialog1.FileName, lstSQL);
                        }
                    }
                    else
                    {
                        MessageBox.Show("没有记录!");
                    }
                }
            }
            catch (System.Exception ex)
            {
                CDebug.SendError(ex.ToString());
            }

            CDebug.ExitMethod("导出数据脚本");
        }

        /// <summary>
        /// 替换连接字符串中的数据库名称
        /// </summary>
        public void strConReplace()
        {
            /*
            string strDB_Temp = CPub.findStrBetween(ado1.S_Con, "Catalog=", ";");

            if (dbInf.sDBNam == "")
                ado1.S_Con = ado1.S_Con.Replace("Catalog=;", "Catalog=" + node1.dbInf.sDBNam + ";");
            else
                ado1.S_Con = ado1.S_Con.Replace(strDB_Temp, node1.dbInf.sDBNam);

            ado2.S_Con = ado1.S_Con;
            */

            TreeNodeDBMgr node1 = (TreeNodeDBMgr)treeView1.SelectedNode;
            string sDBConStr = CDB.getConStr(node1.dbInf);
            ado1.S_Con = sDBConStr;
            ado2.S_Con = sDBConStr;
            CDebug.Send(sDBConStr);
        }

        /// <summary>
        /// 绘制行号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(e.RowBounds.Location.X,
                e.RowBounds.Location.Y,
                dataGridView1.RowHeadersWidth - 4,
                e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                dataGridView1.RowHeadersDefaultCellStyle.Font,
                rectangle,
                dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

    }
}